<?php
namespace Common\Controller;

use Common\Controller\AppframeController;
use Com\Wechat;
use Com\WechatAuth;

class WeixinBaseController extends AppframeController
{

    public $u;
    public $jump_self;
    public $wk;
    public $wxconfig;

    public $wx_u;


    function _initialize()
    {
        parent::_initialize();


        session("j_id",I('get.j_id'));

        $this->wxconfig=F("Config_weixin");

        $this->seo_title = C("SITE_NAME");
        $this->seo_keywords = C("SITE_KEYWORDS");
        $this->seo_description = C("SITE_DESC");

        $this->_get_auth();



        $this->get_user_info();      //获取当前登录用户的信息，并且存入cookie

        $this->get_c_auth();

        $this->get_wx_info();



        if(CONTROLLER_NAME!="Public"&&!IS_AJAX&&ACTION_NAME!="bangding"){

            cookie("jump_self",get_now_url());


        } ;





        //从cookie里读取跳转链接
        $this->jump_self = cookie("jump_self") ? cookie("jump_self") : __ROOT__ . "/";









    }

    public function get_wx_info(){



            $u_inf=$this->wk->userInfo(session("open_id"));





        $this->wx_u=$u_inf;

//            if($u_inf["subscribe"]){
//
//                echo 1;
//                $this->wx_u=$u_inf;
//
//            }else{
//                echo 2;
//
//                $this->wx_u=false;
//
//            }

        if( $this->u["id"]){
            $this->u["avatar"]=$this->wx_u[headimgurl];

        }




        $this->assign("wx_u",$this->wx_u);

    }

    public function  get_c_auth(){


        $s=M("WxToken")->order("id desc")->find();





            $this->wk = new WechatAuth($this->wxconfig["WX_APPID"], $this->wxconfig["WX_APPSECRET"], $s["token"]);



            $this->wk->setJsApiTicket($s["ticket"]);

            $jssign=$this->wk->getSignPackage();

            $this->assign("jssign",$jssign);













    }


    public function get_user_info()
    {

        $userinfo = D("Users")->get_info_id(array("open_id"=>session("open_id")));



        if($userinfo){
            $this->u=$userinfo;

            session("uid",$userinfo["id"]);
        }





    }


    public function _get_auth()
    {

        $token = session("wx_token");
        $open_id=session("open_id");



        if ($open_id&&$token) {

            $auth = new WechatAuth($this->wxconfig["WX_APPID"], $this->wxconfig["WX_APPSECRET"], $token);



        } else {
            $code = I("get.code");

            if ($code) {
                $auth = new WechatAuth($this->wxconfig["WX_APPID"], $this->wxconfig["WX_APPSECRET"]);
                $token = $auth->getAccessToken("code", I("get.code"));

                session(array('expire' => 1000));
                session("wx_token", $token['access_token']);
                session("open_id", $token["openid"]);



            } else {

                $auth = new WechatAuth($this->wxconfig["WX_APPID"], $this->wxconfig["WX_APPSECRET"]);
                $auth->getRequestCodeURL(get_now_url(), "", "snsapi_base");

            }





        }


    }





    public function do_loginout()
    {

        cookie("user", null);
    }


    //发送邮件
    protected function _send_to_active()
    {
        $config = array_merge(F("Config_site"), F("Config_user"));
        if (!$config) {
            $this->error('网站未配置账号激活信息，请联系网站管理员');
        }
        //邮件标题
        $title = $config['USER_REGISTER_EMAIL_TITLE'];
        $user = $this->u;
        $uid = $this->u[id];
        $username = $user[name];

        $activekey = md5($uid . time() . uniqid());
        $users_model = M("Users");

        $result = $users_model->save(array("id" => $uid, "user_activation_key" => $activekey));
        if (!$result) {
            $this->error('激活码生成失败！');
        }

        //生成激活链接
        $url = U('User/active/active', array("hash" => $activekey), "", true);
        //邮件内容
        $template = $config['USER_REGISTER_EMAIL'];
        $content = str_replace(array('http://#link#', '#username#'), array($url, $username), $template);

        $send_result = SendMail($user['email'], $title, $content);

        if ($send_result['error']) {
            $this->error('激活邮件发送失败！');
        }
    }

    /**
     * 加载模板和页面输出 可以返回输出内容
     * @access public
     * @param string $templateFile 模板文件名
     * @param string $charset 模板输出字符集
     * @param string $contentType 输出类型
     * @param string $content 模板输出内容
     * @return mixed
     */
    public function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '')
    {
        //echo $this->parseTemplate($templateFile);
        parent::display($this->parseTemplate($templateFile), $charset, $contentType);
    }

    public function fetch($templateFile = '', $content = '', $prefix = '')
    {
        return parent::fetch($this->parseTemplate($templateFile), $content, $prefix);
    }


    /**
     * 自动定位模板文件
     * @access protected
     * @param string $template 模板文件规则
     * @return string
     */
    public function parseTemplate($template = '')
    {

        $tmpl_path = TEMPLATE_PATH;

        // 获取当前主题名称
        $theme = C('THEME');
        if (C('TMPL_DETECT_THEME')) {// 自动侦测模板主题
            $t = C('VAR_TEMPLATE');
            if (isset($_GET[$t])) {
                $theme = $_GET[$t];
            } elseif (cookie('think_template')) {
                $theme = cookie('think_template');
            }
            if (!file_exists($tmpl_path . "/" . $theme)) {
                $theme = C('THEME');
            }
            cookie('think_template', $theme, 864000);
        }

        if (C('MOBILE_TPL_ENABLED')) {//开启手机模板支持
            if (sp_is_mobile()) {
                if (file_exists($tmpl_path . "/" . $theme . "_mobile")) {
                    $theme = $theme . "_mobile";
                }
            }
        }


        C('THEME', $theme);

        // 获取当前主题的模版路径
        define('THEME_PATH', $tmpl_path . $theme . "/");


        C('SP_VIEW_PATH', $tmpl_path);
        C('DEFAULT_THEME', $theme);

        if (is_file($template)) {
            return $template;
        }
        $depr = C('TMPL_FILE_DEPR');
        $template = str_replace(':', $depr, $template);

        // 获取当前模块
        $module = MODULE_NAME;
        if (strpos($template, '@')) { // 跨模块调用模版文件
            list($module, $template) = explode('@', $template);
        }


        // 分析模板文件规则
        if ('' == $template) {
            // 如果模板文件名为空 按照默认规则定位
            $template = "/" . CONTROLLER_NAME . $depr . ACTION_NAME;
        } elseif (false === strpos($template, '/')) {
            $template = "/" . CONTROLLER_NAME . $depr . $template;
        }

        $file = THEME_PATH . $module . $template . C('TMPL_TEMPLATE_SUFFIX');
        if (!is_file($file)) E(L('_TEMPLATE_NOT_EXIST_') . ':' . $file);
        return $file;
    }


    public function _do_login_data($id)
    {
        $data = M("Users")->where(array("id" => $id))->find();

        $key = lap_password($data[id] . $data[name] . $data['pwd_hash']);
        $result = array(

            "id" => $data[id],
            "name" => $data[name],
            "email" => $data[email],
            "nickname" => $data[nickname],
            "key" => $key,
            "avatar" => $data[avatar],
            "last_login_ip" => $data[last_login_ip],
            "last_login_time" => $data[last_login_time],
            "create_time" => $data[create_time],
            "status" => $data[status],
            "group" => $data[group],
            "score" => $data[score],
            "model" => $data[model],
            "email_status" => $data[email_status],
            "shenhe" => $data[shenhe],


        );
        cookie("user", $result);


    }


    public function _renzheng($code, $phone)
    {

        if (!$code) {

            return array(
                "status" => false,
                "error" => "请填写验证码"
            );


        }

        if ($code != session('code')) {
            return array(
                "status" => false,
                "error" => "验证码错误"
            );

        }


        if ($phone != session('phone')) {

            return array(
                "status" => false,
                "error" => "请填写正确手机号"
            );


        }


        $rst = D("Users")->where(array("name" => $phone))->getField("id");

        $guan_log=D("GuanLog")->where(array("open_id"=>session("open_id")))->find();

        //没有注册的手机号进行注册
        if (!$rst) {

            $data = array(
                "name" => $phone,
                'last_login_ip' => get_client_ip(),
                'create_time' => time(),
                'last_login_time' => time(),
                'status' => 1,
                'email_status' => 1,
                "model" => "Member",
                "pwd_hash" => rand_string(),
                "open_id"=>session("open_id")
            );


            if($guan_log){

                $data["j_id"]=$guan_log["j_id"];

            }

            $uu_id = D("Users")->add($data);







            if (!$uu_id) {


                return array(
                    "status" => false,
                    "error" => "登陆失败！"
                );


            }
            else{

                $this->_get_auth();

                $this->get_user_info();


                return array(
                    "status" => true,
                    "uid" => $uu_id


                );


            }
        }
        else{

            $data=array("id"=>$rst,
                "open_id"=>session("open_id")
                );

            $uu_id = D("Users")->save($data);

            if (!$uu_id) {


                return array(
                    "status" => false,
                    "error" => "更新失败！"
                );



            }else{

                $this->_get_auth();

                $this->get_user_info();

                return array(
                    "status" => true,
                    "uid" => $rst


                );



            }




        }



    }

}